<template>
  <u-form-item
    :label="label"
    :prop="props.data.field"
    :required="props.data.required"
  >
    <u-input
			ref="refAmount"
      v-model="val"
			type="digit"
			inputAlign="right"
      :placeholder="props.data.placeholder"
      :readonly="props.data.readonly"
      :disabled="props.data.disabled"
      @change="onChange"
      @blur="onBlur"
    >
			<template #prefix>¥</template>
      <template #suffix>元</template>
    </u-input>
  </u-form-item>
</template>

<script setup lang="ts">
import { ref, nextTick, watch } from 'vue'
import { useProps } from '../hooks/props'
import { isNumber } from '../../../utils/util'

const props = defineProps<{ data: Record<string, any>; form: Record<string, any> }>()
const emits = defineEmits(['valueChange'])

const refAmount = ref()

const { label } = useProps(props)
const val = ref()
const last = ref()

const onChange = (value: any) => {
	val.value = value
	if (isNumber(value)) {	
		last.value = val.value
		emitsHandler(val.value)
	} else {	
		val.value = last.value
		emitsHandler(val.value)
	}
}

const onBlur = () => {
	val.value = parseFloat(val.value)
	if (props.data.min || props.data.min == 0) {
		if (val.value < props.data.min) {			
			val.value = props.data.min
			last.value = val.value
			emitsHandler(val.value)
		}
	}
	if (props.data.max || props.data.max == 0) {
		if (val.value > props.data.max) {
			val.value = props.data.max
			last.value = val.value
			emitsHandler(val.value)
		}
	}
}

const emitsHandler = (value: any) => {
	const num = +value
	const valFixed = (Math.round(num * 100) / 100).toFixed(2)	
	nextTick(() => {
		val.value = valFixed
	})
	emits('valueChange', { name: props.data.field, value: valFixed })
}

watch(
	() => props.data.defaultVal,
	() => {
		val.value = props.data.defaultVal
		if (emits) {
			emits('valueChange', { name: props.data.field, value: val.value })
		}
	},
	{ immediate: true }
)
</script>

<style lang="scss" scoped>
</style>
